package com.itcast.rabbitmq.work;

import com.itcast.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @ClassName Recv1
 * @Description TODO
 * @Author Trigger Wu
 * @Date 2018/9/2810:12
 * @Version 1.0
 **/

public class Recv1 {
    private final static String QUEUE_NAME = "test_queue_work";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        // 监听队列，手动返回完成
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                String routingKey = envelope.getRoutingKey();
                String contentType = properties.getContentType();
                long deliveryTag = envelope.getDeliveryTag();

                String message = new String(body);
                System.out.println(" [x] Received '" + message + "'");
                //休眠
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 返回确认状态
                channel.basicAck(deliveryTag, false);
            }
        });
//
//        // 获取消息
//        while (true) {
//            DefaultConsumer delivery = consumer.
//            String message = new String(delivery.getBody());
//            System.out.println(" [x] Received '" + message + "'");
//            //休眠
//            Thread.sleep(10);
//            // 返回确认状态
//            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
//        }
    }
}
